#include "mystdio.h"

myFILE* my_fopen(const char *path, const char *type)
{
    int flag = 0;
    bool iscreate = false;
    mode_t mode = 0666;
    if (strcmp(type, "r") == 0)
    {
        flag = O_RDONLY;
    }
    else if (strcmp(type, "w") == 0)
    {
        flag = (O_WRONLY|O_CREAT|O_TRUNC);
        iscreate = true;
    }
    else if (strcmp(type, "w") == 0)
    {
        flag = (O_WRONLY | O_CREAT | O_APPEND);
        iscreate = true;
    }
    else {}

    int fd = 0;
    if (iscreate)
    {
        fd = open(path, flag, mode);
    }
    else
    {
        fd = open(path, flag);
    }

    if (fd < 0) return NULL;

    myFILE *fp = (myFILE*)malloc(sizeof(myFILE));
    if (!fp) return NULL;

    fp->flags = FLUSH_LINE;
    fp->fileno = fd;
    fp->cap = MAX_SIZE;
    fp->pos = 0;
}

void my_fflush(myFILE *fp)
{
    write(fp->fileno, fp->buffer, fp->pos);
    fp->pos = 0;
}

ssize_t my_fwrite(myFILE *fp, const char *data, int len)
{
    bool isfinish = false;
    int nOfSize = len;
    while (!isfinish)
    {
        if (nOfSize - fp->pos > fp->cap)
        {
            memcpy(fp->buffer + fp->pos, data, fp->cap - fp->pos - 1);
            nOfSize -= fp->cap - fp->pos - 1;
            data += fp->cap - fp->pos - 1;
            fp->pos = fp->cap - 1;
            my_fflush(fp);
        }
        else
        {
            memcpy(fp->buffer + fp->pos, data, nOfSize);
            fp->pos += nOfSize;
        }
    }

    if((fp->flags & FLUSH_LINE) && fp->buffer[fp->pos-1] == '\n')
    {
        my_fflush(fp);
    }

    return len;
}

void my_fclose(myFILE *fp)
{
    my_fflush(fp);
    close(fp->fileno);
    free(fp);
    fp = NULL;
}